package com.hsq.commons.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class CookieUtil {
	
	private static Log log = LogFactory.getLog(CookieUtil.class);
	
	public static void addCookie(HttpServletResponse response,Map<String,String> m,int time,String serverHost) {
		  for(Object key  : m.keySet()){   
			  log.info("__set__key:"+key+"______value:"+m.get(key)+"______________________________");
			  addCookie(response,(String) key,m.get(key),time,serverHost);
			  
		  }
	}
	
	public static void delCookie(HttpServletResponse response,String key){
		Cookie delCookie=new Cookie(key, null); 
		delCookie.setMaxAge(0);
		delCookie.setPath("/");
		response.addCookie(delCookie); 
	}
	
	
	public static void delAllCookie(HttpServletResponse response,HttpServletRequest request){
		Cookie cookies[]=request.getCookies();
		Cookie sCookie=null;
		for(int i=0;i<cookies.length-1;i++){
			sCookie=cookies[i];
			delCookie(response,sCookie.getName());
		}
	}
	
	
	public static void addCookie(HttpServletResponse response,String key,String value,int time,String serverHost) {
		Cookie cookie=new Cookie(key, DESPlus.encrypt(value)); 
		cookie.setMaxAge(time);
		cookie.setDomain( serverHost); 
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	public static Map<String,String> getCookie(HttpServletRequest request) {
		Cookie cookies[]=request.getCookies(); 
		Cookie sCookie=null; 
		Map<String,String> m = new HashMap<String,String>();
		if(cookies==null )return m;
		for(int i=0;i<cookies.length;i++){
			sCookie=cookies[i];  
			if(sCookie==null ) continue;
			log.info("__get__key:"+sCookie.getName()+"______value:"+sCookie.getValue()+"______");
			if("JSESSIONID".equals(sCookie.getName())|| "YGAUTH_USER".equals(sCookie.getName())) continue;
			m.put(sCookie.getName(),sCookie.getValue());
		}
		return m;
	}
	
	public static void getCookie(HttpServletRequest request,Map<String,String> m) {
		m.putAll(getCookie(request));
	}
	
	public static String getCookieValue(HttpServletRequest request,String key) {
		String v = getCookie(request).get(key);
		if(v!=null){
			return (String)  DESPlus.decrypt(v);
		}
		return "";
	}
}
